package client.view;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;

import common.WrapperTask;

public class MultiKeys implements KeyListener
{
	private View view;
	private Timer timer;
	private TimerTask task;  
	private int delay = 25;
    private final Set<Integer> pressedKeys = new HashSet<Integer>(); // Set of currently pressed keys

	public MultiKeys(View view) {
		this.view = view;
		timer = new Timer();
	}

	// Invoked when the Timer fires
	Runnable runnable = new Runnable() {
	    @Override
	    public void run() {
	    	if (pressedKeys.size() == 1) {
	    		if (pressedKeys.contains(SWT.ARROW_UP)) {
	    			view.setUserCommand(1);
	    		}
	    		else if (pressedKeys.contains(SWT.ARROW_DOWN)) {
	    			view.setUserCommand(2);
	    		}
	    		else if (pressedKeys.contains(SWT.ARROW_RIGHT)) {
	    			view.setUserCommand(4);
	    		}
	    		else if (pressedKeys.contains(SWT.ARROW_LEFT)) {
	    			view.setUserCommand(3);
	    		}
	    		
	    		pressedKeys.clear();
	    	}
	    	else if (pressedKeys.size() > 1) {
	    		if (pressedKeys.contains(SWT.ARROW_UP)) {
	    			if (pressedKeys.contains(SWT.ARROW_RIGHT)) {
	    				//Move Up and Right (Horizontal)
	    				view.setUserCommand(5);
	    			}
	    			else if (pressedKeys.contains(SWT.ARROW_LEFT)) {
	    				//Move Up and Left (Horizontal)
	    				view.setUserCommand(6);
	    			}
	    		}
	    		else if (pressedKeys.contains(SWT.ARROW_DOWN)) {
	    			if (pressedKeys.contains(SWT.ARROW_RIGHT)) {
	    				//Move Down and Right (Horizontal)
	    				view.setUserCommand(7);
	    			}
	    			else if (pressedKeys.contains(SWT.ARROW_LEFT)) {
	    				//Move Down and Left (Horizontal)
	    				view.setUserCommand(8);
	    			}
	    		}
	    		
	    		pressedKeys.clear();
	    	}
	    }
	};

	@Override
	public void keyPressed(KeyEvent e) {
		pressedKeys.add(e.keyCode);
		
		// Start the Timer when the first key is pressed
   		if (!view.getLockControls() && pressedKeys.size() == 1)
   		{	
   			task = new WrapperTask(runnable);
		    timer.schedule(task, delay);  
   		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		pressedKeys.remove(e.keyCode);
		
		// Stop the Timer when all keys have been released
   		if (!view.getLockControls() && pressedKeys.size() == 0)
   		{
   			task.cancel();
   		}
	}

	public void dispose() {
		timer.cancel();
		timer.purge();
	}
}